package com.livery.app.model.tables;

import java.util.ArrayList;
import java.util.List;

import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;

import com.livery.data.Repair;

public class RepairTableModel extends AbstractTableModel{
	
	private List<Repair> repairList;
	private ArrayList<TableModelListener> listeners = new ArrayList<TableModelListener>();
	private final String[] columnHeaders= {"Klient","Samochod","Pracownik wydający", "Pracownik przyjmujący", "Data wydania" , "Termin zwrotu", "Data Zwrotu","Cena"};
	
	public RepairTableModel(List<Repair> repairList){
		this.repairList = repairList;
	}
	
	public RepairTableModel(){
		this.repairList = new ArrayList<Repair>() ;
	}
	
	
	
	public List<Repair> getRepairList() {
		return repairList;
	}

	public void setRepairList(List<Repair> repairList) {
		this.repairList = repairList;
	}

	@Override
	public int getColumnCount() {
		return 4;
	}

	@Override
	public int getRowCount() {
		return repairList.size();
	}

	@Override
	public Object getValueAt(int r, int c) {
		switch(c)
		{
		case 0 : return repairList.get(r).getDate().toString();
		case 1 : return repairList.get(r).getDescription();
		case 2 : return repairList.get(r).getCost();
		case 3 : return repairList.get(r).getCar().getModel() + " "+repairList.get(r).getCar().getMake();
		
		default : return null;
		}
	}
	
	@Override
	public Class<?> getColumnClass(int columnIndex) {
		switch(columnIndex){
		case 2: return Integer.class;
		default: return String.class;
		}
		
		
	}
	
	public void addRow(Repair repair){
		repairList.add(repair);
		TableModelEvent event = new TableModelEvent(this,repairList.size()-1,repairList.size()-1,TableModelEvent.ALL_COLUMNS,TableModelEvent.INSERT);
		for(TableModelListener tml : listeners){
			tml.tableChanged(event);
		}
	}
	
	public void updateRow(int index, Repair repair){
		
		repairList.set(index, repair);
		TableModelEvent event = new TableModelEvent( this, index, index, TableModelEvent.ALL_COLUMNS, TableModelEvent.UPDATE );
		for(TableModelListener tml : listeners){
			tml.tableChanged(event);
		}
	}
	
	public void removeRow(Repair repair){
		int index = repairList.indexOf(repair);
		repairList.remove(index);
		
		TableModelEvent event = new TableModelEvent( this, index, index, TableModelEvent.ALL_COLUMNS, TableModelEvent.DELETE );
		for(TableModelListener tml : listeners){
			tml.tableChanged(event);
		}
		
	}
	
	@Override
	public String getColumnName(int column) {
		
		return columnHeaders[column];
	}
	
	@Override
	public void addTableModelListener(TableModelListener l) {
		if(listeners.contains(l)){
			return; 
		}
		
		listeners.add(l);
	}
	
	@Override
	public void removeTableModelListener(TableModelListener l) {
		listeners.remove(l);
	}

}
